<template>
  <t-drawer
    title="数据授权"
    placement="right"
    :width="640"
    :visible="visible"
    :destroyOnClose="true"
    @close="closeDrawer"
  >
    <div class="project-drawer-container">
      <div class="header">
        <a-button @click="handleAllRoles('add')" icon="plus" type="primary">
          批量授权
        </a-button>
        <a-button @click="handleAllRoles('delete')" type="link">
          批量取消
        </a-button>
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="auto"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
          :tree-config="{
            rowField: 'id',
            parentField: 'pid',
            childrenField: 'children',
            expandAll: true,
            reserve: true,
          }"
          :row-config="{ keyField: 'id' }"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent"
        >
          <vxe-table-column type="checkbox" width="60"></vxe-table-column>
          <vxe-column
            field="orgName"
            title="组织/项目名称"
            min-width="250"
            tree-node
            align="left"
          >
          </vxe-column>
          <vxe-column field="authorize" title="授权状态">
            <template #default="{ row }">
              <span v-if="row.authorize == 0" class="error">
                未授权
              </span>
              <span v-else class="success">已授权</span>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            title="操作"
            fixed="right"
            width="130"
            v-if="parameter.id != 34"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  @click="handleRole(row, 'add')"
                  type="link"
                  v-if="row.authorize == 0"
                >
                  授权
                </a-button>
                <a-button
                  @click="handleRole(row, 'delete')"
                  type="link"
                  v-else
                  class="danger"
                >
                  取消授权
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="footer">
        <a-button @click="closeDrawer">
          取消
        </a-button>
      </div>
    </div>
  </t-drawer>
</template>

<script>
import { flatTreeData } from "@/utils/util.js";
import { axios } from "@/utils/request";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      tableData: [],
      loading: false,
      tableCheckRecords: [],
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getTableData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleAllRoles(type) {
      if (this.tableCheckRecords.length === 0) {
        this.$message.warn("请先选择需要操作的数据");
        return;
      }
      let codes = this.tableCheckRecords.map((v) => v.orgCode);
      this.requestRole(codes.toString(), type);
    },

    handleRole(row, type) {
      this.requestRole(row.orgCode, type);
    },

    requestRole(codes, type) {
      let { parameter } = this;
      this.loading = true;
      axios
        .post(
          `/mdata/sysRoleProject/addOrUpdate`,
          {
            proCodes: codes,
            type,
            roleId: parameter.id,
          },
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          if (res.statusCode === 200) {
            this.getTableData();

            this.tableCheckRecords = [];
            this.$refs.xTable.clearCheckboxRow();

            this.$message.success(res.message, 1.5);
          } else {
            this.$message.error(res.message, 1.5);
          }
        })
        .catch((_) => {
          this.loading = false;
        })
        .finally((_) => {});
    },

    //查询列表
    getTableData() {
      this.loading = true;
      let { parameter } = this;
      axios
        .post(
          `/mdata/organization/getTreeSysOrganizationAll?roleId=${parameter.id}&type=roleBindOrg`,
          {},
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          this.tableData = res?.data ?? [];
          this.$refs.xTable.setAllTreeExpand(true);
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    //监听table全选
    selectAllEvent({ checked, records }) {
      if (checked) {
        this.tableCheckRecords.push(...records);
        this.tableCheckRecords = this.uniqueBy(
          this.tableCheckRecords,
          "orgCode"
        );
      } else {
        this.tableCheckRecords = [];
      }
    },

    //监听table复选框
    selectChangeEvent({ checked, records, row }) {
      let { orgCode } = row;
      if (checked) {
        this.tableCheckRecords.push(...records);
        this.tableCheckRecords = this.uniqueBy(
          this.tableCheckRecords,
          "orgCode"
        );
      } else {
        this.tableCheckRecords = this.tableCheckRecords.filter(
          (v) => orgCode != v.orgCode
        );
      }
    },

    //json数组去重
    uniqueBy(arr, key) {
      const unique = {};
      return arr.filter((item) => {
        if (!unique[item[key]]) {
          unique[item[key]] = true;
          return true;
        }
        return false;
      });
    },

    closeDrawer() {
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-drawer-body {
  padding: 0 !important;
  height: calc(100% - 55px);
  .project-drawer-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .header {
      padding: 10px 20px;
      box-sizing: border-box;
      display: flex;
      .ant-btn-link {
        margin-left: 10px;
        color: #ff5722;
      }
    }
    .main {
      overflow: hidden;
      flex: 1;
      .success {
        color: green;
      }
      .error {
        color: red;
      }
    }
    .footer {
      padding: 10px 20px;
      box-sizing: border-box;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
